/*
 * Copyright (C) 2009 Giacomo Spigler
 * CopyPolicy: Released under the terms of the GNU GPL v3.0.
 */

//Single webcam demo

#include <iostream>
#include <cv.h>
#include <highgui.h>
#include <stdio.h>

#include "../libcam.h"

using namespace std;


int main(int argc, char **args) {
	int ww=640;
	int hh=480;
	int fps=30;

	const char *dev="/dev/video1";
	const char *rdev="/dev/video0";

	printf("Usage is:\n  %s -w width -h height -d device -f fps\n\n", args[0]);

	//Processing arguments
	for(int i=1; i<argc-1; i++) {
		string a=args[i];
		if(a=="-w") {
			ww=atoi(args[i+1]);
		}
		else if(a=="-h") {
			hh=atoi(args[i+1]);
		}
		else if(a=="-d") {
			dev=args[i+1];
		}
		else if(a=="-f") {
			fps=atoi(args[i+1]);
		}

	}


	// 1) Instance a Camera object
	Camera c(dev, ww, hh, fps);
	Camera rc(rdev, ww, hh, fps);



	cvNamedWindow("l", CV_WINDOW_AUTOSIZE);
	cvNamedWindow("r", CV_WINDOW_AUTOSIZE);

	IplImage *l=cvCreateImage(cvSize(ww, hh), 8, 3);
	unsigned char *l_=(unsigned char *)l->imageData;

	IplImage *r=cvCreateImage(cvSize(ww, hh), 8, 3);
	unsigned char *r_=(unsigned char *)l->imageData;

	bool pressing = 0;
	char lname[32];
	char rname[32];
	for(int photoNum = 0;;) {
		// 2) Grab next frame
		c.Update();
		rc.Update();
		// 3) Convert to OpenCV format  (default is YUYV, stored into c.data[] )
		c.toIplImage(l);
		rc.toIplImage(r);

		cvShowImage("l", l);
		cvShowImage("r", r);

		int c = cvWaitKey(10) & 255;

//		printf("%c, %d\n", c, c);
		if(c == 27)
			break;
		else if(c == ' ' && !pressing) {
			sprintf(lname, "left%d.jpg", photoNum);
			sprintf(rname, "right%d.jpg", photoNum++);
			printf("%s\n", lname);
			cvSaveImage(lname, l);
			cvSaveImage(rname, r);
			pressing = 1;
		}
		else
			pressing = 0;
	}

	cvDestroyWindow("l");
	cvDestroyWindow("r");
	cvReleaseImage(&l);
	cvReleaseImage(&r);

	// 4) Automatic cleanup is done when the app terminates

	return 0;
}





